from PyQt5 import QtGui
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import *
import sys
import socket
from threading import Thread


class Sender(QWidget):
    # 初始化界面
    def __init__(self):
        QWidget.__init__(self)
        # 设置窗口的大小和位置
        self.setGeometry(600, 300, 500, 360)
        # 设置标题
        self.setWindowTitle("聊天室")
        # 添加背景
        palette = QtGui.QPalette()
        bg = QtGui.QPixmap(r"./img/background.jpg")
        palette.setBrush(self.backgroundRole(), QtGui.QBrush(bg))
        self.setPalette(palette)
        self.add_ui()
        # 与服务器连接
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.local_addr = ("127.0.0.1", 7788)
        self.client_socket.connect(self.local_addr)

        # 启动线程
        self.work_thread()

    # 设置界面当中的组件
    def add_ui(self):
        # 多行文本显示，显示所有的聊天信息
        self.content = QTextBrowser(self)
        self.content.setGeometry(30, 30, 450, 150)

        # 单行文本，消息发送框
        self.message = QLineEdit(self)
        self.message.setGeometry(30, 220, 450, 30)
        self.message.setPlaceholderText("请输入发送内容")

        # 发送按钮
        self.button = QPushButton("发送", self)
        self.button.setFont(QFont("微软雅黑", 10, QFont.Bold))
        self.button.setGeometry(400, 270, 60, 30)

    # 发送消息
    def send_msg(self):
        msg = self.message.text()
        self.client_socket.send(msg.encode())
        if msg.upper() == "Q":
            self.client_socket.close()
            self.destroy()
        self.message.clear()

    # 接收消息
    def recv_msg(self):
        while True:
            try:
                data = self.client_socket.recv(1024).decode()
                print(data)
                data = data + "\n"
                self.content.append(data)
            except:
                exit()

    # 点击按钮发送消息
    def btn_send(self):
        self.button.clicked.connect(self.send_msg)

    # 线程处理
    def work_thread(self):
        Thread(target=self.btn_send).start()
        Thread(target=self.recv_msg).start()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    sender = Sender()
    sender.show()
    sys.exit(app.exec())
